from flask import request, g

from common.libs import Helper
from common.libs.Restful import Restful
from common.libs.UrlManager import UrlManager
from common.models.foods.Food import Food
from common.models.order.PayOrder import PayOrder
from common.models.order.PayOrderItem import PayOrderItem
from . import api_route, db


@api_route.route('/my/orderlist/', methods=['POST'])
def orderlist():
    req = request.values
    status = int(req['status']) if 'status' in req else 0
    member = g.member_info

    query = db.session.query(PayOrder).filter_by(member_id=member.id)
    if status == -8: #等待付款
        query = query.filter(PayOrder.status == -8)
    elif status == -7: #待付款
        query = query.filter(PayOrder.status == 1, PayOrder.express_status == -7, PayOrder.comment_status == 0)
    elif status == -6: #待确认
        query = query.filter(PayOrder.status == 1, PayOrder.express_status == -6, PayOrder.comment_status == 0)
    elif status == -5: #待评价
        query = query.filter(PayOrder.status == 1, PayOrder.express_status == -5, PayOrder.comment_status == 0)
    elif status == 1: #已完成
        query = query.filter(PayOrder.status == 1, PayOrder.express_status == 1, PayOrder.comment_status == 0)
    else:
        query = query.filter(PayOrder.status == 0)

    tmp_order_list = query.order_by(PayOrder.id.desc()).all()
    order_list = []
    if not tmp_order_list:
        return Restful.success(data=[], msg='暂无订单数据')
    pay_order_ids = Helper.selectFilterObj(tmp_order_list, 'id')
    pay_order_item_list = PayOrderItem.query.filter(PayOrderItem.pay_order_id.in_(pay_order_ids)).all()
    food_ids = Helper.selectFilterObj(pay_order_item_list, 'food_id')
    food_map = Helper.getDictFilterField(Food, Food.id, 'id', food_ids)
    pay_order_item_map = {}
    if pay_order_item_list:
        for item in pay_order_item_list:
            if item.pay_order_id not in pay_order_item_map:
                pay_order_item_map[item.pay_order_id] = []

            tmp_food_info = food_map[item.food_id]
            pay_order_item_map[item.pay_order_id].append({
                'id': item.id,
                'food_id': item.food_id,
                'quantity': item.quantity,
                'pic_url': UrlManager.buildImageUrl(tmp_food_info.main_image),
                'name': tmp_food_info.name
            })
        for item in tmp_order_list:
            order_list.append({
                'status': item.pay_status,
                'status_desc': item.status_desc,
                'date': item.created_time.strftime("%Y-%m-%d %H%M%S"),
                'order_number': item.order_number,
                'order_sn': item.order_sn,
                'note': item.note,
                'total_price': str(item.total_price),
                'goods_list': pay_order_item_map[item.id],
            })
    return Restful.success(data=order_list)